import DEFAULT_AVATAR from '@/assets/imgs/default-avatar.jpg';
import CommentCard from '@/components/CommentCard';
import {
  getCommentCountByTargetIdAndTypeUsingPost,
  listCommentVoParentByPageUsingPost,
} from '@/services/backend/commentController';
import { doThumbUsingPost } from '@/services/backend/commentThumbController';
import { LikeOutlined } from '@ant-design/icons';
import {
  Avatar,
  Card,
  Divider,
  Image,
  List,
  message,
  Radio,
  RadioChangeEvent,
  Skeleton,
  Space,
  Typography,
} from 'antd';
import { CheckboxGroupProps } from 'antd/lib/checkbox';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import React, { useEffect, useState } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';

dayjs.extend(relativeTime);

const options: CheckboxGroupProps<string>['options'] = [
  { label: '默认', value: 'createTime' },
  { label: '最热', value: 'thumbNum' },
];

interface Props {
  id: number;
  type?: string;
}

/**
 * 默认搜索的评论类型
 */
const DEFAULT_COMMENT_TYPE = 'project';

const EssayCommentCard: React.FC<Props> = (props) => {
  const { id, type = DEFAULT_COMMENT_TYPE } = props;
  //查询评论的排序规则
  const [commentSortedField, setCommentSortedField] = useState<string>('createTime');
  //评论数据
  const [commentData, setCommentData] = useState<API.PostVO[]>([]);
  //是否有更多评论
  const [hasMore, setHasMore] = useState<boolean>(true);
  //评论数量
  const [commentCount, setCommentCount] = useState<number>();
  //当前页
  const [current, setCurrent] = useState<number>(1);
  // 使用Map存储每个评论的回复状态，键为评论ID
  const [replyStates, setReplyStates] = useState<Map<number, boolean>>(new Map());

  /**
   * 加载评论数据
   * @param sortField 排序字段
   * @param pageNum 当前页面
   */
  const loadCommentData = async (sortField: string, pageNum?: number) => {
    //默认分页大小
    const pageSize = 5;
    // 使用传入的页码或当前状态中的页码
    const currentPage = pageNum || current;

    try {
      const { code, data } = await listCommentVoParentByPageUsingPost({
        sortField,
        sortOrder: 'descend',
        targetId: id,
        type: type,
        pageSize: pageSize,
        current: currentPage,
      });
      if (code === 0 && data) {
        // 如果是加载更多（页码大于1），则追加数据而不是替换
        if (currentPage > 1) {
          setCommentData((prevData) => [...prevData, ...(data?.records ?? [])]);
        } else {
          setCommentData(data?.records ?? []);
        }
        const hasMore = Number(data.current) < Number(data.pages);
        setHasMore(hasMore);
      }
    } catch (e: any) {
      message.error(e.message);
    }
  };

  /**
   * 加载评论个数
   */
  const loadCommentCount = async () => {
    const { code, data } = await getCommentCountByTargetIdAndTypeUsingPost({
      targetId: id,
      type: type,
    });
    if (code === 0) {
      setCommentCount(data);
    }
  };

  /**
   * 当Radio发生变化时,处理评论排序字段
   * @param value
   */
  const handleCommentSortedFieldChange = ({ target: { value } }: RadioChangeEvent) => {
    setCommentSortedField(value);
    //获取评论数据
    loadCommentData(value);
  };

  /**
   * 切换特定评论的回复状态
   * @param commentId 评论ID
   */
  const toggleReplyState = (commentId: number) => {
    setReplyStates((prevStates) => {
      const newStates = new Map(prevStates);
      newStates.set(commentId, !prevStates.get(commentId));
      return newStates;
    });
  };
  /**
   * 处理评论点赞
   * @param commentId
   */
  const handleThumb = async (commentId: number) => {
    try {
      await doThumbUsingPost({
        commentId,
      });
      await loadCommentData(commentSortedField);
    } catch (e: any) {
      message.error(e.message);
    }
  };

  /**
   * 初始化组件时加载的数据
   */
  useEffect(() => {
    // 初始化时重置页码为1
    setCurrent(1);
    loadCommentData(commentSortedField, 1);
    loadCommentCount();
  }, []);

  return (
    <Card
      tabList={[
        {
          key: '评论',
          tab: '评论',
        },
      ]}
      variant={'borderless'}
    >
      <Card
        id={'post-comment-card'}
        title={<div>{commentCount}条评论</div>}
        extra={
          <Radio.Group
            options={options}
            value={commentSortedField}
            onChange={handleCommentSortedFieldChange}
            optionType="button"
            buttonStyle="solid"
          />
        }
        variant={'borderless'}
        style={{
          boxShadow: 'none',
        }}
        styles={{
          header: {
            borderBottom: 'none',
          },
        }}
      >
        {/*评论*/}
        <CommentCard
          type={type}
          targetId={id}
          callback={async () => {
            // 初始化时重置页码为1
            setCurrent(1);
            await loadCommentData(commentSortedField, 1);
            await loadCommentCount();
          }}
        />
        {/*帖子*/}
        <InfiniteScroll
          dataLength={commentData.length}
          next={async () => {
            // 计算下一页的页码
            const nextPage = current + 1;
            // 先更新状态
            setCurrent(nextPage);
            // 使用新的页码加载数据
            await loadCommentData(commentSortedField, nextPage);
          }}
          hasMore={hasMore}
          endMessage={
            !hasMore ? (
              <p style={{ textAlign: 'center' }}>
                <Divider plain>已经到底了 🤐</Divider>
              </p>
            ) : (
              <></>
            )
          }
          loader={<Skeleton avatar paragraph={{ rows: 4 }} active />}
        >
          <List<API.CommentVO>
            split={false}
            itemLayout={'vertical'}
            dataSource={commentData}
            renderItem={(item, index) => {
              const isReplying = replyStates.get(item?.id ?? -1) || false;

              //获取评论的actions
              const commentActions: React.ReactNode[] = [];
              //时间展示
              commentActions.push(<span key={'time'}>{dayjs(item.createTime).fromNow()}</span>);
              //点赞展示
              if (item.hasThumb) {
                commentActions.push(
                  <Typography.Link key={'thumb'} onClick={() => handleThumb(item?.id ?? -1)}>
                    <Space size={4}>
                      <LikeOutlined />
                      {item.thumbNum}
                    </Space>
                  </Typography.Link>,
                );
              } else {
                commentActions.push(
                  <a key={'thumb'} onClick={() => handleThumb(item?.id ?? -1)}>
                    <Space size={4}>
                      <LikeOutlined />
                      {item.thumbNum}
                    </Space>
                  </a>,
                );
              }
              //回复展示
              commentActions.push(
                <a onClick={() => toggleReplyState(item?.id ?? -1)} key={'reply'}>
                  {isReplying ? '取消' : '回复'}
                </a>,
              );

              return (
                <>
                  <List.Item
                    itemID={index + ''}
                    styles={{
                      actions: {
                        marginLeft: '50px',
                      },
                    }}
                    actions={commentActions}
                  >
                    <List.Item.Meta
                      avatar={<Avatar size={'large'} src={item.user?.avatar ?? DEFAULT_AVATAR} />}
                      title={item.user?.username ?? '无名氏'}
                      description={item.user?.profile ?? '这个人很懒,什么也没留下~'}
                    />
                    <div style={{ marginLeft: '50px' }}>
                      <div className={'text-base  break-all whitespace-pre-line'}>
                        {item.content}
                      </div>
                      <Space size={'middle'}>
                        {item.pictureList?.map((picture) => (
                          <Image key={picture} className={'z-0'} width={80} src={picture} />
                        ))}
                      </Space>
                    </div>
                  </List.Item>
                  {/*回复评论Card*/}
                  {isReplying ? (
                    <div style={{ marginLeft: '50px' }}>
                      <CommentCard
                        type={type}
                        avatar={false}
                        parentId={item.id}
                        targetId={id}
                        callback={async () => {
                          // 初始化时重置页码为1
                          setCurrent(1);
                          await loadCommentData(commentSortedField, 1);
                          await loadCommentCount();
                          toggleReplyState(item?.id ?? -1);
                        }}
                      />
                    </div>
                  ) : (
                    <></>
                  )}
                  {/*子评论*/}
                  {item.childrenList?.length !== 0 ? (
                    <div style={{ marginLeft: '50px' }}>
                      <List<API.PostVO>
                        split={false}
                        itemLayout={'vertical'}
                        dataSource={item.childrenList}
                        renderItem={(item, index) => {
                          //获取评论的actions
                          const commentActions: React.ReactNode[] = [];
                          //时间展示
                          commentActions.push(
                            <span key={'time'}>{dayjs(item.createTime).fromNow()}</span>,
                          );
                          //点赞展示
                          if (item.hasThumb) {
                            commentActions.push(
                              <Typography.Link
                                key={'thumb'}
                                onClick={() => handleThumb(item?.id ?? -1)}
                              >
                                <Space size={4}>
                                  <LikeOutlined />
                                  {item.thumbNum}
                                </Space>
                              </Typography.Link>,
                            );
                          } else {
                            commentActions.push(
                              <a key={'thumb'} onClick={() => handleThumb(item?.id ?? -1)}>
                                <Space size={4}>
                                  <LikeOutlined />
                                  {item.thumbNum}
                                </Space>
                              </a>,
                            );
                          }
                          return (
                            <>
                              <List.Item
                                itemID={index + ''}
                                styles={{
                                  actions: {
                                    marginLeft: '50px',
                                  },
                                }}
                                actions={commentActions}
                              >
                                <List.Item.Meta
                                  avatar={
                                    <Avatar
                                      size={'default'}
                                      src={item.user?.avatar ?? DEFAULT_AVATAR}
                                    />
                                  }
                                  title={item.user?.username ?? '无名氏'}
                                  description={item.user?.profile ?? '这个人很懒,什么也没留下~'}
                                />
                                <div style={{ marginLeft: '50px' }}>
                                  <div className={'text-base  break-all whitespace-pre-line'}>
                                    {item.content}
                                  </div>
                                  <Space size={'middle'}>
                                    {item.pictureList?.map((picture) => (
                                      <Image
                                        key={picture}
                                        className={'z-0'}
                                        width={80}
                                        src={picture}
                                      />
                                    ))}
                                  </Space>
                                </div>
                              </List.Item>
                            </>
                          );
                        }}
                      />
                    </div>
                  ) : (
                    <></>
                  )}
                </>
              );
            }}
          />
        </InfiniteScroll>
      </Card>
    </Card>
  );
};

export default EssayCommentCard;
